<?php

namespace app\health\service;

use app\health\model\HealthUserLog;
use think\migration\command\seed\Run;

/**
 * 会员接口请求日志服务类
 */
class UserApiLogService
{
    /**
     * 接口路径白名单
     * @param $path
     * @return bool
     */
    private static function whiteList($path): bool
    {
        if (strpos($path, '/tracking/') !== false) {
            return true;
        }
        $userId     = request()->user_id ?? 0;
        $userMobile = request()->user_mobile ?? '';
        if (!$userId && !$userMobile) {
            return true;
        }
        return false;
    }

    /**
     * 记录用户请求日志
     * @param $response
     * @param $responseCode
     * @return HealthUserLog|true
     */
    public static function record($response, $responseCode)
    {
        $apiPath = request()->path();
        if (!self::whiteList($apiPath)) {
            $param                  = request()->param();
            $data                   = [];
            $data['user_id']        = request()->user_id ?? 0;
            $data['user_mobile']    = request()->user_mobile ?? '';
            $data['api_path']       = request()->path();
            $data['request_method'] = request()->method();
            $data['request_ip']     = request()->ip();
            $data['request_param']  = $param;
            $data['request_time']   = date('Y-m-d H:i:s', request()->time());
            $data['request_header'] = request()->header();
            $data['running_time']   = debug('health_run_start', 'health_run_end', 6);
            $data['response_code']  = $responseCode;
            $data['response']       = $response;
            $data['created_at']     = date('Y-m-d H:i:s');
            return HealthUserLog::create($data);
        }
        return true;
    }
}